/*
 * @Descripttion: 路由配置文件
 * @version:
 * @Author: lhl
 * @Date: 2024-09-01 20:44:16
 * @LastEditors: lhl
 * @LastEditTime: 2024-09-20 11:07:44
 */
import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router';
import NProgress from '@/utils/nprogress';
import { usePermissionStore } from '@/store/permission';
import { useUserInfo } from '@/store/user';

// 布局组件
export const Layout = () => import('@/layout/Index.vue');

export const constantRoutes: Array<RouteRecordRaw> = [
  {
    path: '/redirect',
    component: Layout,
    meta: {
      title: '加载中...',
      hidden: true,
      sort: 102
    },
    name: 'Redirect',
    children: [
      {
        path: '/redirect/:path(.*)',
        name: 'Redirect',
        component: () => import('@/views/redirect/Redirect.vue')
      }
    ]
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/login/Login.vue'),
    meta: { title: '登录页面', hidden: true }
  },
  {
    path: '/',
    // name: 'Dashboard',
    component: Layout,
    redirect: '/dashboard',
    children: [
      {
        path: '/dashboard',
        component: () => import('@/views/dashboard/Dashboard.vue'),
        // 用于 keep-alive 功能，需要与 SFC 中自动推导或显式声明的组件名称一致
        // 参考文档: https://cn.vuejs.org/guide/built-ins/keep-alive.html#include-exclude
        name: 'Dashboard',
        meta: {
          title: '首页',
          showParent: true,
          icon: 'Menu',
          affix: true,
          keepAlive: true
        }
      },
      {
        path: '/401',
        component: () => import('@/views/error-page/401.vue'),
        meta: { title: '401', hidden: true }
      },
      {
        path: '/404',
        component: () => import('@/views/error-page/404.vue'),
        meta: { title: '404', hidden: true }
      }
    ]
  }
  // {
  //   // vue-router@4的变化，舍弃*通配符 放在最后
  //   // 官方文档：https://next.router.vuejs.org/zh/guide/migration/index.html#%E5%88%A0%E9%99%A4%E4%BA%86-%EF%BC%88%E6%98%9F%E6%A0%87%E6%88%96%E9%80%9A%E9%85%8D%E7%AC%A6%EF%BC%89%E8%B7%AF%E7%94%B1
  //   path: '/:pathMatch(.*)*',
  //   name: '404',
  //   component: () => import('@/views/error-page/404.vue')
  // }
];

const router = createRouter({
  // createWebHashHistory() hash模式带 # 符号，createWebHistory() 无 # 符号
  // 注意：如果使用 history 模式，需要后端配置支持，否则刷新页面会导致路由丢失
  history: createWebHistory(),
  routes: constantRoutes,
  // ts没有用到 from参数 所以加个下划线 变成成占位符 用到时候在写成 form 防止 ts/eslint 报错
  scrollBehavior(to, _from, savedPosition) {
    // 如果有 hash，滚动到 hash 位置
    if (to.hash) {
      return {
        el: to.hash,
        // scrollBehavior 的 behavior: 'smooth' 属性依赖于浏览器的平滑滚动支持。如果浏览器不支持平滑滚动，将会使用默认的滚动行为
        behavior: 'smooth'
      };
    }
    // 如果有缓存位置，滚动到缓存位置
    if (savedPosition) {
      return savedPosition;
    }
    // 否则，滚动到顶部
    return { top: 0, left: 0, behavior: 'smooth' };
  }
});

// 白名单路由
const whiteList = ['/login'];

router.beforeEach(async (to, from, next) => {
  NProgress.start();
  // const { user, permission } = useStore();
  const user = useUserInfo();
  const permission = usePermissionStore();
  const hasToken = localStorage.getItem('authToken');
  if (hasToken) {
    // 登录成功，跳转到首页
    if (to.path === '/login') {
      next({ path: '/' });
      NProgress.done();
    } else {
      const hasGetUserInfo = user.roles.length > 0;
      if (hasGetUserInfo) {
        if (to.matched.length === 0) {
          if (from.name) {
            next({ name: from.name as any });
          } else {
            next('/401');
          }
        } else {
          next();
        }
      } else {
        try {
          await user.getUserInfo();
          const roles = user.roles;
          const accessRoutes: any = await permission.generateRoutes(roles);
          console.log(accessRoutes, 'vaccessRoutes==');
          // 只添加不存在的路由
          // 检查路由是否在 router.options.routes 中已存在
          accessRoutes.forEach((route: any) => {
            if (!router.hasRoute(route.name)) {
              // 假设 route.name 是路由的唯一标识
              router.addRoute(route);
              console.log(`添加路由: ${route.name}`); // 输出添加的路由
            }
          });
          next({ ...to, replace: true });
        } catch (error) {
          console.log(error, 'error');
          // 移除 token 并跳转登录页
          await user.resetToken();
          next(`/login?redirect=${to.path}`);
          NProgress.done();
        }
      }
    }
  } else {
    // 未登录可以访问白名单页面(登录页面)
    if (whiteList.indexOf(to.path) !== -1) {
      next();
    } else {
      next(`/login?redirect=${to.path}`);
      NProgress.done();
    }
  }
});

// 本身接受 to form 参数，但是没有用到
router.afterEach(() => {
  NProgress.done();
});

/**
 * 重置路由
 */
export function resetRouter() {
  const permissionStore = usePermissionStore();
  permissionStore.routes.forEach((route) => {
    const name = route.name;
    if (name && router.hasRoute(name)) {
      router.removeRoute(name);
    }
  });
}

export default router;
